Env.Singleton = function() {
	this.registry = {};
	this.instances = {};
};

Env.Singleton.prototype = {

	/**
	 * Registers the singleton class for later use.
	 */
	register: function(name, cls) {
		Core.assert(!this.registry[name], "Singleton with the given name '" + name + "' is already registered.");
		Core.assert(cls.prototype.__clear, "Singleton with the given name '" + name + "' has no __clear method");
		
		this.registry[name] = cls;
		this.instances[name] = new cls();
		
		return this.instances[name];
	},
	
	/**
	 * Creates new instance of the registered singleton.
	 * For test purpose only.
	 */
	newInstance: function(name) {
		Core.assert(this.registry[name], "Singleton with the given name not found.");
		return new (this.registry[name])();
	},
	
	/**
	 * Clears the state of all registered singletons.
	 * This method is intended for use in testing after each invoked test case.
	 */
	restoreInitialState: function() {
		Object.each(this.instances, function(singleton) {
			singleton.__clear();
		});
	}
};

Env.Singleton = new Env.Singleton();